package com.example.pcdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
/*
网络
 */
import com.rfid.api.GFunction;
import com.rfid.spec.NetDataReport;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

public class NetActivity extends Activity  implements View.OnClickListener {
    public static final int RESULT_OK = 1;
    public static final int RESULT_CANCEL = 2;
    private static final int INVENTORY_MSG = 1;
    private static final int NET_OK = 3;
    private static final int NET_ERROR =4;
    private  Button btn_Find=null;
    private  Button btn_FindOk=null;
    private  Button btn_SetNet=null;
    private Button btn_FindCancel=null;
    private ListView list_inventory_net = null;// inventory list
    private Thread m_inventoryThread = null;// The thread of inventory
    private  List<InventoryNetReport> inventoryList =new ArrayList<InventoryNetReport>();
    private  InventoryNetAdapter inventoryNetAdapter=null;
    Socket socket = null;
    MulticastSocket ms = null;
    DatagramPacket dp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net);
        btn_Find=findViewById(R.id.btn_Find);
        btn_Find.setOnClickListener(this);
        btn_FindCancel=findViewById(R.id.btn_FindCancel);
        btn_FindCancel.setOnClickListener(this);
        btn_FindOk=findViewById(R.id.btn_FindOk);
        btn_FindOk.setOnClickListener(this);
        btn_SetNet=findViewById(R.id.btn_EditNet);
        btn_SetNet.setOnClickListener(this);
        list_inventory_net=findViewById(R.id.list_net);
        inventoryNetAdapter = new InventoryNetAdapter(this, inventoryList);
        list_inventory_net.setAdapter(inventoryNetAdapter);
        list_inventory_net.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //onListItemClick(position);

            }
        });
      // String conStr = String.format("RDType=%s;CommType=NET;RemoteIp=%s;RemotePort=%s", "PC8001", "255.255.255.255", 6688);
        MainActivity.m_reader.PC_NetOpen();
    }
    void onListItemClick(int index) {
        b_inventoryThreadRun=false;
        InventoryNetReport netReport=   inventoryList.get(index);
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("IP", netReport.getIp());
        intent.putExtras(bundle);
        this.setResult(RESULT_OK, intent);
        this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case  R.id.btn_Find:
                if (m_inventoryThread !=null && m_inventoryThread.isAlive())
                {
                    b_inventoryThreadRun=false;
                    btn_Find.setText("开始");
                }else
                {
                    inventoryList.clear();
                    this.inventoryNetAdapter.notifyDataSetChanged();
                    m_inventoryThread = new Thread(new InventoryThread());
                    m_inventoryThread.start();
                    btn_Find.setText("停止");
                }

                //new  udpBroadCast().start();
                //new  udpReceive().start();
                break;
            case R.id.btn_FindCancel:
                if (m_inventoryThread !=null && m_inventoryThread.isAlive())
                {
                    Toast.makeText(this, "请先停止搜索!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                MainActivity.m_reader.PC_NetClose();
                this.finish();
                break;
            case  R.id.btn_FindOk:
                if (m_inventoryThread !=null && m_inventoryThread.isAlive())
                {
                    Toast.makeText(this, "请先停止搜索!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                InventoryNetReport netReport=FindNetReport();
                if (netReport==null)
                {
                    Toast.makeText(this, "请选择IP!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("IP", netReport.getIp());
                intent.putExtras(bundle);
                this.setResult(RESULT_OK, intent);
                this.finish();
                break;
            case R.id.btn_EditNet:
                if (m_inventoryThread !=null && m_inventoryThread.isAlive())
                {
                    Toast.makeText(this, "请先停止搜索!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                InventoryNetReport netReport1=FindNetReport();
                if (netReport1==null)
                {
                    Toast.makeText(this, "请选择IP!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                new UpdateIp(netReport1).start();

                break;
            default:
                break;
        }
    }

    private  byte[] StringToByte(String[] strings)
    {
        byte[] b=new byte[strings.length];
        for ( int i=0;i<strings.length;i++)
        {
            b[i]= (byte)Integer.parseInt(strings[i]);
        }
        return  b;
    }
    private InventoryNetReport FindNetReport()
    {
        boolean m_find=false;
        InventoryNetReport netReport=null;
        for (int i=0;i<inventoryList.size();i++)
        {
            netReport=   inventoryList.get(i);
            if (netReport.isChecked())
            {
                m_find=true;
                break;
            }
        }
        if (!m_find)return  null;
        return  netReport;
    }
    private  class UpdateIp extends Thread
    {
       InventoryNetReport m_NetReport=null;
        public UpdateIp(InventoryNetReport netReport)
        {
           this.m_NetReport=netReport;
        }
        @Override
        public void run() {
            String[] strIps=m_NetReport.getIp().split("\\.");
            String[] strMasks=m_NetReport.getMask().split("\\.");
            String[] strGrateway=m_NetReport.getGrateway().split("\\.");
            byte[] pIp=StringToByte(strIps);
            byte[] pMask=StringToByte(strMasks);
            byte[] pGrateway=StringToByte(strGrateway);
            int iret=MainActivity.m_reader.PC_SetNet(pIp,pMask,pGrateway);
            if (iret==0)
            {
                Message msg = mHandler.obtainMessage();
                msg.what = NET_OK;
                mHandler.sendMessage(msg);
            }
            else
            {
                Message msg = mHandler.obtainMessage();
                msg.what = NET_ERROR;
                mHandler.sendMessage(msg);
            }
        }
    }
    private boolean b_inventoryThreadRun = false;
    private class InventoryThread implements Runnable
    {
        @Override
        public void run() {
            b_inventoryThreadRun = true;
            while (b_inventoryThreadRun)
            {
                SystemClock.sleep(100);
                int iret =MainActivity.m_reader.PC_NetInventory();
                if (iret==0)
                {
                   int count= MainActivity.m_reader.PC_GetNetReportCount();
                   if (count <=0)continue;
                    Vector<Object> tagList = new Vector<Object>();
                    Object tagReport = MainActivity.m_reader.PC_GetNetDataReport((byte)1);
                    while (tagReport !=null)
                    {

                         tagReport = MainActivity.m_reader.PC_GetNetDataReport((byte)1);
                         if (tagReport !=null)
                         {
                             tagList.add(tagReport);
                         }

                         MainActivity.m_reader.PC_GetNetDataReport((byte)2);

                         continue;
                    }
                    Message msg = mHandler.obtainMessage();
                    msg.what = INVENTORY_MSG;
                    msg.obj = tagList;
                    mHandler.sendMessage(msg);
                }

            }
        }
    }
    public static class InventoryNetReport
    {
       private String Ip;
        private String Mask;
        private String Grateway;
        private  String Mac;
        private  boolean Checked=false;
        public  InventoryNetReport()
       {
         super();
        }

        public InventoryNetReport(String ip, String mask,String grateway,String mac)
        {
            this.setIp(ip);
            this.setMask(mask);
            this.setGrateway(grateway);
            this.setMac(mac);
        }

        public boolean isChecked() {
            return Checked;
        }

        public void setChecked(boolean checked) {
            Checked = checked;
        }

        public String getIp() {
            return Ip;
        }

        public void setIp(String ip) {
            this.Ip = ip;
        }

        public String getMask() {
            return Mask;
        }

        public void setMask(String mack) {
            Mask = mack;
        }

        public String getGrateway() {
            return Grateway;
        }

        public void setGrateway(String grateway) {
            Grateway = grateway;
        }

        public String getMac() {
            return Mac;
        }

        public void setMac(String mac) {
            Mac = mac;
        }
    }
    static  public class InventoryNetAdapter extends BaseAdapter
    {
       private List<InventoryNetReport> list;
       private LayoutInflater inflater;
       private  NetActivity netActivity;
       public  InventoryNetAdapter(Context context,List<InventoryNetReport> adapters)
       {
           this.list = adapters;
           inflater = LayoutInflater.from(context);
           netActivity=(NetActivity) context;
       }
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        @SuppressLint({"ResourceType", "WrongViewCast"})
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            InventoryNetReport netReport=(InventoryNetReport) this.getItem(position);
            final ViewHolder viewHolder;
            if (convertView == null)
            {
                viewHolder = new ViewHolder();
                convertView = inflater
                        .inflate(R.xml.inventorynet_title, null);
                viewHolder.mCheckBox=(CheckBox )convertView.findViewById(R.id.tv_inventorySelect);
                viewHolder.mCheckBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        for (int i=0;i<list.size();i++)
                        {
                            InventoryNetReport report=  list.get(i);
                            if (i ==position)
                            {
                                report.setChecked(true);
                            }else
                            {
                                report.setChecked(false);
                            }
                        }
                        netActivity.inventoryNetAdapter.notifyDataSetChanged();
                    }
                });
                viewHolder.mTextMac = (EditText) convertView
                        .findViewById(R.id.tv_inventoryMac);

                viewHolder.mTextIP = (EditText) convertView
                        .findViewById(R.id.tv_inventoryIp);
                viewHolder.mTextIP.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        for (int i=0;i<list.size();i++)
                        {
                            InventoryNetReport report=  list.get(i);
                            if (i ==position)
                            {
                                report.setIp(viewHolder.mTextIP.getText().toString());
                            }

                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                viewHolder.mTextMask=(EditText) convertView
                        .findViewById(R.id.tv_inventoryMask);
                viewHolder.mTextMask.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        for (int i=0;i<list.size();i++)
                        {
                            InventoryNetReport report=  list.get(i);
                            if (i ==position)
                            {
                                report.setMask(viewHolder.mTextMask.getText().toString());
                            }

                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                viewHolder.mTextGrateway = (EditText) convertView
                        .findViewById(R.id.tv_inventoryGrateway);
                viewHolder.mTextGrateway.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        for (int i=0;i<list.size();i++)
                        {
                            InventoryNetReport report=  list.get(i);
                            if (i ==position)
                            {
                                report.setGrateway(viewHolder.mTextGrateway.getText().toString());
                            }

                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                convertView.setTag(viewHolder);
            }
            else
            {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.mCheckBox.setChecked(netReport.isChecked());
            viewHolder.mTextMac.setText(netReport.getMac());
            viewHolder.mTextIP.setText(netReport.getIp());
            viewHolder.mTextMask.setText(netReport.getMask());
            viewHolder.mTextGrateway.setText(netReport.getGrateway());

            return convertView;
        }
        private class ViewHolder
        {
            public CheckBox mCheckBox;
            public EditText mTextMac;
            public EditText mTextIP;
            public EditText mTextMask;
            public EditText mTextGrateway;
        }

    }

    private Handler mHandler = new MyHandler(this);
    private static class MyHandler extends Handler
    {
        private final WeakReference<NetActivity> mActivity;
        public  MyHandler(NetActivity activity)
        {
            mActivity = new WeakReference<NetActivity>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            NetActivity pt = mActivity.get();
            if (pt == null)
            {
                return;
            }
            boolean b_find = false;
            switch (msg.what)
            {
                case INVENTORY_MSG:// 搜索到IP
                    Vector<Object> tagList = (Vector<Object>) msg.obj;
                    if (!pt.inventoryList.isEmpty())
                    {
                        pt.inventoryList.clear();
                    }
                    for (int i = 0; i < tagList.size(); i++)
                    {
                        NetDataReport report=(NetDataReport) tagList.get(i);
                        for (int j = 0; j < pt.inventoryList.size(); j++)
                        {
                            InventoryNetReport inventoryNetReport=pt.inventoryList.get(j);
                            if (report.m_Ip.equals(inventoryNetReport.getIp()))
                            {
                                b_find=true;
                                break;
                            }
                        }
                        if (!b_find)
                        {
                            //(String ip, String mask,String grateway,String mac)
                           pt.inventoryList.add(new InventoryNetReport(report.m_Ip,report.m_Mask,report.m_Grateway,report.m_Mac));
                        }
                    }
                    pt.inventoryNetAdapter.notifyDataSetChanged();
                    break;
                case NET_OK:
                    Toast.makeText(pt, "修改成功!", Toast.LENGTH_SHORT).show();
                    break;
                case NET_ERROR:
                    Toast.makeText(pt, "修改失败!", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    }
}

